<template>
    <div style="width: 95%;margin: auto;">
        <el-form :inline="true" :model="roleForm" class="demo-form-inline">
            <el-form-item style="width: 180px;">
                <el-input v-model="roleForm.rname" placeholder="请输入角色名" clearable style="width: 200px;">
                </el-input>
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-input v-model="roleForm.remark" placeholder="备注" clearable />
            </el-form-item>
            <el-form-item style="width: 180px;">
                <el-button type="primary" @click="findAll(1)">查询</el-button>
                <el-button @click="resetForm()">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 新增和修改对话框 -->
    <div style="width: 95%;margin: auto;">
        <el-button type="primary" @click="showDialog()" :icon="Plus"> 新增</el-button>
        <el-button type="primary" @click="batchedDeleteByIds()" :icon="Delete"> 批量删除</el-button>
    </div>
    <br>
    <div>
        <!-- 新增用户和修改对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="25%" draggable>
            <!-- 新增用户表单 -->
            <el-form :inline="true" :model="dialog.role" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="dialog.role.rname" placeholder="请输入新角色名" clearable
                        style="width: 200px;height: 35px;" />
                </el-form-item>

                <el-input v-model="dialog.role.remark" :rows="2" type="textarea" placeholder="输入备注信息"
                    style="width: 340px;margin-top: 20px;" />
                <el-form-item style="margin-top: 20px;">
                    <el-button type="primary" @click="insertAndUpdateRole">{{ dialog.btnText }}</el-button>
                    <el-button type="primary" @click="clearFormData">重置</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>

    <!-- 所有角色详细信息 -->
    <el-table :data="rolePage.roles" style="width: 95% ; margin:auto" @selection-change="handleSelectionChange">
        <!-- 添加复选框选项 -->
        <el-table-column type="selection" width="55" />
        <el-table-column fixed prop="rid" label="编号" width="80" />
        <el-table-column prop="rname" label="角色名" width="120" />
        <el-table-column prop="remark" label="备注" width="150" />
        <el-table-column label="操作" min-width="160" fixed="right">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
                    修改
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                <el-button link type="warning" size="small" @click="handleMenus(scope.row)">分配菜单</el-button>
            </template>
        </el-table-column>
    </el-table>

    <div>
        <!-- 角色分配菜单对话框 -->
        <el-dialog v-model="dialogMenu.visible" title="更新角色菜单" width="25%" draggable>
            <!-- 
                属性：
                    :data 表示树形控件显示数据（数据要求是树形结构）
                    show-checkbox表示属性结构节点 可操作
                    node-key="id"表示唯一数值，建议使用后端数据主键
                    :default-expanded-keys 表示设置默认展开节点
                    :default-checked-keys 设置默认选中数据
                    :props 设置显示数据结构
            -->
            <el-tree style="max-width: 600px" ref="menuTree" :data="dialogMenu.data" show-checkbox node-key="mid"
                :default-checked-keys="dialogMenu.defaultKeys" :props="defaultProps" />
            <el-button type="primary" @click="updateRoleMenus">更新</el-button>
        </el-dialog>
    </div>

    <div style="width: 95%;margin: 10px auto;">
        <el-pagination background layout="prev, pager, next" v-model:page-size="roleForm.pageSize"
            v-model:current-page="roleForm.pageNum" :total="roleForm.total" @current-change="findAll" />
    </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Delete, Edit, Female, Male, HomeFilled, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'



const rolePage = reactive({
    roles: [],//存放后端查询用户数据变量
})
//声明一个对象用于条件查询
let roleForm = ref({
    rname: "",
    remark: "",
    menus: [],
    pageNum: 0,
    pageSize: 5,
    total: 0,
})
//根据条件查询信息
const findAll = async (currentpage) => {
    roleForm.value.pageNum = currentpage;
    let res = await request.post("/roles/findAll", roleForm.value);
    if (res.data.success) {
        rolePage.roles = res.data.data.list;
        roleForm.value.pageNum = res.data.data.pageNum;
        roleForm.value.pageSize = res.data.data.pageSize;
        roleForm.value.total = res.data.data.total;
    }
}
//定义对话框属性
let dialog = ref({
    visible: false,
    title: '',
    btnText: '',
    role: {
        rname: '',
        remark: '',
    },
})
const clearFormData = () => {
    dialog.value.role = {};
}
//重置表单
const resetForm = () => {
    roleForm.value.rname = "";
    roleForm.value.remark = "";
    roleForm.value.pageNum = 0;
    roleForm.value.pageSize = 5;
    roleForm.value.total = 0;
}
const showDialog = () => {
    dialog.value.role = { rname: '', remark: '', };
    dialog.value.visible = true;
    dialog.value.title = "新增角色";
    dialog.value.btnText = "添加";

}
const handleEdit = (index, row) => {
    dialog.value.role = row;
    dialog.value.visible = true;
    dialog.value.title = "修改角色";
    dialog.value.btnText = "修改";
}
const insertAndUpdateRole = async () => {
    if (dialog.value.btnText == "添加") {
        let res = await request.post("/roles/insert", dialog.value.role);
        if (res.data.success) {
            ElMessage.success("添加成功");
            //清空表单
            dialog.value.role = {};
            //关闭对话框
            dialog.value.visible = false;
            //刷新页面
            findAll(1);
        }
    } else {
        let res = await request.put("/roles/update", dialog.value.role);
        if (res.data.success) {
            ElMessage.success("修改成功");
            //清空表单
            dialog.value.role = {};
            //关闭对话框
            dialog.value.visible = false;
            //刷新页面
            findAll(roleForm.value.pageNum);
        }
    }
}
const handleDelete = async (row) => {
    let res = await request.delete(`/roles/deleteById/${row.rid}`, { params: row });
    if (res.data.success) {
        ElMessage.success("删除成功");
        findAll(1);
    } else ElMessage.error("删除失败");
}
// 批量删除
//定义数组，存放批量删除元素集合
const roles = reactive({
    rolesIds: [],
})
//复选框被选择触发函数
const handleSelectionChange = (rows) => {
    roles.rolesIds = rows;
}
const batchedDeleteByIds = async () => {
    //1.判断数组中是否包含删除元素
    if (roles.rolesIds.length <= 0) {
        ElMessage.warning("请选择删除项...")
        return; //结束
    }
    let ids = [];
    //2.遍历数组，获取所有id值
    for (let i = 0; i < roles.rolesIds.length; i++) {
        let r = roles.rolesIds[i];
        console.log(r);
        //把值添加到数组中
        ids.push(r.rid);
    }
    const idsStr = ids.toString();
    //3.发送异步请求
    let response = await request.delete(`/roles/deleteByIds/${ids}`, { params: { idsStr } });
    if (response.data.success) {
        //显示提示信息
        ElMessage.success("批量删除成功")
        //刷新页面
        findAll(1);
    } else ElMessage.error("批量删除失败");
}
//定义对话框变量
const dialogMenu = reactive({
    visible: false,
    roleId: null,
    data: [],//所有菜单数据
    defaultKeys: []
})
const defaultProps = {
    children: 'children',
    label: 'mname',
}
//通过绑定到指定元素实例
const menuTree = ref();
const handleMenus = async (role) => {
    dialogMenu.defaultKeys = []; //清空数组
    //1.把当前role数据保存下
    dialogMenu.roleId = role.rid;
    //查询所有菜单数据
    let res = await request.get("/menu/menus");
    if (res.data.success) {
        dialogMenu.data = res.data.data;
    }
    //设置默认选项
    //获取当前角色关联所有菜单
    let menus = role.menus;
    //遍历集合
    menus.map(m => { //遍历一节菜单数据
        m.children.map(subMenu => {//遍历二级菜单mid
            //把所有二级菜单保存到 defaultkeys集合中
            dialogMenu.defaultKeys.push(subMenu.mid);
        })
    })
    //2.显示对话框
    dialogMenu.visible = true;
}

//更新指定角色菜单函数
const updateRoleMenus = async () => {
    //menuTree.value.getCheckedNodes()  获取所有被选中的节点 (中间状态的阶段未被获取)。返回集合
    //menuTree.value.getHalfCheckedNodes() 获取所有中间状态节点对象集合
    let treeMenus = menuTree.value.getCheckedNodes().concat(menuTree.value.getHalfCheckedNodes());
    //    let trees =  menuTree.value.getCheckedKeys().concat(menuTree.value.getHalfCheckedKeys());
    //发送请求，把数据传递给后端接口
    let res = await request.put(`/roles/updateMenusByRoleId/${dialogMenu.roleId}`, treeMenus);
    if (res.data.success) {
        //显示提示信息
        ElMessage.success("更新菜单成功");
        //2.查询角色
        findAll(1);
        //关闭对话框
        dialogMenu.visible = false;
    } else ElMessage.error("更新菜单失败");
}
onMounted(() => {
    findAll(1);
});
</script>